package com.zhuoyue.biz.core.command.cmd.common.faa;

import com.alibaba.fastjson.JSONObject;
import com.zhuoyue.biz.core.api.dao.GroupMapper;
import com.zhuoyue.biz.core.api.domain.DeviceAndGatewayDO;
import com.zhuoyue.biz.core.api.domain.Group;
import com.zhuoyue.biz.core.api.domain.ZigbeeDeviceProperty;
import com.zhuoyue.biz.core.api.dto.req.ControlReq;
import com.zhuoyue.biz.core.api.service.GatewayRedisService;
import com.zhuoyue.biz.core.command.cmd.common.faa.base.BaseCmd;
import com.zhuoyue.biz.core.command.service.CmdSqlHandleService;
import com.zhuoyue.common.constant.ColorfulBulbLampMode;
import com.zhuoyue.common.constant.ControlType;
import com.zhuoyue.common.utils.CmdUtils;
import com.zhuoyue.common.utils.Time;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @Author zhanghui
 * @Date: 2021/06/16/9:30
 * @Description:
 */
@Repository
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ColorfulBulbLampTwo0Faa0B03 extends BaseCmd {

    private final CmdSqlHandleService cmdSqlHandleService;

    private final RedisTemplate redisTemplate;

    private final GatewayRedisService gatewayRedisService;

    private final GroupMapper groupMapper;
    /**
     * 区间
     */
    private static final String DURATION = "duration";
    /**
     * 00
     */
    private static final String ZERO_ZERO = "00";

    private static ColorfulBulbLampTwo0Faa0B03 colorfulBulbLampTwo0Faa0B03Static;

    /**
     * 在构造方法执行，给静态变量赋值（@Autowired注入的对象无法在静态方法中获取到）
     */
    @PostConstruct
    public void init() {
        colorfulBulbLampTwo0Faa0B03Static = this;
    }

    /**
     * 是否为群组
     */
    private static boolean isGroup = false;

    public static String control(DeviceAndGatewayDO deviceAndGatewayDO, ControlReq controlReq, boolean isGroupControl) {
        isGroup = isGroupControl;
        String cmd = "";
        String data;
        String duration = "00";
        String gatewayMac = deviceAndGatewayDO.getGatewayMac();
        String zigbeeMac = deviceAndGatewayDO.getZigbeeMac();
        String groupId = "";

        if (isGroupControl) {
            groupId = controlReq.getActions().get("groupId").toString();
        }

        //从数据库中取duration值，默认为0
        if (!isGroupControl) {
            ZigbeeDeviceProperty zigbeeDeviceProperty = colorfulBulbLampTwo0Faa0B03Static.cmdSqlHandleService.getDeviceProperty(deviceAndGatewayDO.getId());
            if (zigbeeDeviceProperty == null) {
                duration = "00";
            } else {
                JSONObject property = JSONObject.parseObject(zigbeeDeviceProperty.getProperty());
                if (property.get(DURATION) == null || property.get(DURATION) == "") {
                    duration = "00";
                } else {
                    duration = CmdUtils.intToHexTwo((Integer) property.get(DURATION) * 2 + 1);
                }
            }
        } else {
            Group group = colorfulBulbLampTwo0Faa0B03Static.groupMapper.selectById(groupId);
            JSONObject groupAction = JSONObject.parseObject(group.getAction());
            if (groupAction == null || groupAction.get(DURATION) == null || groupAction.get(DURATION) == "") {
                duration = "00";
            } else {
                duration = CmdUtils.intToHexTwo((Integer) groupAction.get("duration") * 2 + 1);
            }
        }
        //从子索引到帧尾
        String cmd8ToEnd = "";
        switch (controlReq.getControlType()) {
            //打开，白光亮度为FF
            case ControlType.TURN_ON_REQUEST:
                cmd8ToEnd = "1F0000000102000001FF";
                break;
            //关闭
            case ControlType.TURN_OFF_REQUEST:
                cmd8ToEnd = "090000000102";
                break;
            //延时关闭
            case ControlType.TIMING_TURN_OFF_REQUEST:
                int delayTime = Integer.parseInt(controlReq.getActions().get("delayTime").toString());
                cmd8ToEnd = "0D000000" + "03" + CmdUtils.intToHexFour(delayTime) + "02";
                break;
            //取消延时
            case ControlType.CANCEL_DELAY_REQUEST:
                cmd8ToEnd = "010000000C";
                break;
            //设置亮度
            case ControlType.SET_BRIGHTNESS_PERCENTAGE_REQUEST:
                //根据duration值判断灯光模式是直接还是渐渐
                if (ZERO_ZERO.equals(duration)) {
                    data = "1F0000000102";
                } else {
                    data = "1F0000000202";
                }
                cmd8ToEnd = data + "00" + duration + "01" + CmdUtils.intToHexTwo(Integer.parseInt(controlReq.getActions().get("brightness").toString()));
                break;
            //设置颜色
            case ControlType.SET_COLOR_REQUEST:
                //根据duration值判断灯光模式是直接还是渐渐
                if (ZERO_ZERO.equals(duration)) {
                    data = "7F0000000103";
                } else {
                    data = "7F0000000203";
                }
                cmd8ToEnd = data + "00" + duration + "01"
                        + CmdUtils.intToHexTwo(Integer.parseInt(controlReq.getActions().get("red").toString()))
                        + CmdUtils.intToHexTwo(Integer.parseInt(controlReq.getActions().get("green").toString()))
                        + CmdUtils.intToHexTwo(Integer.parseInt(controlReq.getActions().get("blue").toString()));
                break;
            //设置模式
            case ControlType.SET_MODE_REQUEST:
                String modeState = controlReq.getActions().get("modeState").toString();
                //不同的场景有特定的帧
                switch (modeState) {
                    case ColorfulBulbLampMode.COLORFUL_GRADIENT:
                        cmd8ToEnd += "0B000000090101";
                        break;
                    case ColorfulBulbLampMode.COLORFUL_JUMP:
                        cmd8ToEnd += "0F0000000A01000501";
                        break;
                    case ColorfulBulbLampMode.BREATHING_LAMP:
                        cmd8ToEnd += "7B0000000B0301"
                                + "F00000";
                        break;
                    default:
                        cmd8ToEnd = "";
                        break;
                }
                break;
            default:
                cmd8ToEnd = "";
                break;
        }
        if ("".equals(cmd8ToEnd)) {
            cmd = "";
        } else {
            cmd = cmdDeal(cmd8ToEnd, gatewayMac, zigbeeMac);
        }

        String redisKeyPrefix;
        redisKeyPrefix = zigbeeMac;

        //若是延时关，则将关闭时间点的时间戳存到redis
        if (ControlType.TIMING_TURN_OFF_REQUEST.equals(controlReq.getControlType()) && !isGroupControl) {
            int delayTime = Integer.parseInt(controlReq.getActions().get("delayTime").toString());
            long closeTime = Time.toLongMilli(LocalDateTime.now()) + delayTime * 1000L;
            colorfulBulbLampTwo0Faa0B03Static.redisTemplate.opsForValue().set(redisKeyPrefix + "_delayTime", closeTime, delayTime, TimeUnit.SECONDS);
        }
        //若是关闭，则可能需要发送取消延时关的命令
        if (ControlType.CANCEL_DELAY_REQUEST.equals(controlReq.getControlType()) && !isGroupControl) {
            Boolean isDeleted = colorfulBulbLampTwo0Faa0B03Static.redisTemplate.delete(redisKeyPrefix + "_delayTime");
            //有延时关并已删除redis中的数据，则发送命令
            if (isDeleted) {
                String cancelDelayCmd = cmdDeal("010000000C", gatewayMac, zigbeeMac);
                colorfulBulbLampTwo0Faa0B03Static.gatewayRedisService.writeDataToGateway(gatewayMac, cancelDelayCmd);
                try {
                    Thread.sleep(200);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
        }

        return cmd;
    }

    /**
     * 处理灯带控制器2.0数据帧的公共部分, 从命令标识写OD（1）到数据长度（7）
     *
     * @return
     */
    private static String cmdDeal(String cmd8TtoEnd, String gatewayMac, String deviceMacOrGroupCode) {
        //od索引
        String cmd1 = "02";
        String cmd2;
        String cmd5 = "0FAA";
        //可变索引
        String cmd6 = "FF";
        if (isGroup) {
            cmd2 = "02";
        } else {
            cmd2 = "01";
        }

        String cmd1To6 = cmd1 + cmd2 + gatewayMac + deviceMacOrGroupCode + cmd5 + cmd6;
        String cmd7 = CmdUtils.getDateLength(cmd8TtoEnd);

        return cmd1To6 + cmd7 + cmd8TtoEnd;
    }
}
